// 扫描仪配置
const SCANNER_CONFIG = {
  delay: 100, // 扫描仪输入延迟时间(ms)
  minLength: 8, // 最小条码长度
  maxLength: 20, // 最大条码长度
  maxInputTime: 800, // 最大输入时间(ms)
  maxKeyInterval: 60, // 最大按键间隔(ms)
};

export class BarcodeScanner {
  constructor(options = {}) {
    this.config = { ...SCANNER_CONFIG, ...options };
    this.buffer = '';
    this.timeout = null;
    this.lastKeyTime = 0;
    this.keyPressCount = 0;
    this.isProcessing = false;
    this.startTime = 0;
    this.onScan = options.onScan || (() => {});
    this.isEnabled = true;

    // 绑定方法到实例
    this.handleInput = this.handleInput.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  init() {
    this.attachListeners();
  }

  destroy() {
    this.detachListeners();
  }

  attachListeners() {
    document.addEventListener('keydown', this.handleInput);
    window.addEventListener('focus', this.handleFocus);
    window.addEventListener('blur', this.handleBlur);
  }

  detachListeners() {
    document.removeEventListener('keydown', this.handleInput);
    window.removeEventListener('focus', this.handleFocus);
    window.removeEventListener('blur', this.handleBlur);
    this.clearTimeout();
  }

  handleInput(event) {
    if (!this.isEnabled) return;

    const key = event.key;
    const currentTime = Date.now();

    // 检查是否有输入框处于焦点状态
    if (this.isInputFocused()) {
      return;
    }

    // 如果正在处理扫描仪输入，忽略新的输入
    if (this.isProcessing) {
      return;
    }

    // 如果是回车键，处理扫描结果
    if (key === 'Enter') {
      event.preventDefault();
      this.processInput();
      return;
    }

    // 如果是可打印字符，添加到缓冲区
    if (key.length === 1 && key.charCodeAt(0) >= 32) {
      // 记录扫描开始时间
      if (this.buffer === '') {
        this.startTime = currentTime;
        this.keyPressCount = 0;
      }

      this.buffer += key;
      this.keyPressCount++;

      this.clearTimeout();

      // 设置新的定时器
      this.timeout = setTimeout(() => {
        this.processInput();
      }, this.config.delay);
    }

    this.lastKeyTime = currentTime;
  }

  processInput() {
    if (!this.buffer.trim() || this.isProcessing) {
      return;
    }

    this.isProcessing = true;
    const scannedCode = this.buffer.trim();

    // 验证扫描输入
    if (this.validateScannerInput(scannedCode)) {
      this.onScan(scannedCode);
    }

    this.reset();
  }

  validateScannerInput(code) {
    // 检查扫描码长度
    if (code.length < this.config.minLength || code.length > this.config.maxLength) {
      return false;
    }

    // 检查是否为纯数字条码
    if (!/^\d+$/.test(code)) {
      return false;
    }

    // 检查输入速度
    const totalInputTime = this.lastKeyTime - this.startTime;
    if (totalInputTime > this.config.maxInputTime) {
      return false;
    }

    // 检查按键间隔
    const avgInterval = totalInputTime / this.keyPressCount;
    if (avgInterval > this.config.maxKeyInterval) {
      return false;
    }

    return true;
  }

  isInputFocused() {
    const activeElement = document.activeElement;
    return (
      activeElement &&
      (activeElement.tagName === 'INPUT' ||
        activeElement.tagName === 'TEXTAREA' ||
        activeElement.contentEditable === 'true' ||
        activeElement.classList.contains('el-input__inner') ||
        activeElement.classList.contains('el-textarea__inner') ||
        activeElement.classList.contains('el-select') ||
        activeElement.closest('.el-select') ||
        activeElement.closest('.el-date-picker'))
    );
  }

  reset() {
    this.buffer = '';
    this.keyPressCount = 0;
    this.lastKeyTime = 0;
    this.startTime = 0;
    this.isProcessing = false;
    this.clearTimeout();
  }

  clearTimeout() {
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
  }

  handleFocus() {
    this.isEnabled = true;
  }

  handleBlur() {
    this.isEnabled = false;
  }

  enable() {
    this.isEnabled = true;
  }

  disable() {
    this.isEnabled = false;
  }
} 